#!/usr/bin/env python

import os
import sys
from os.path import getsize, join, splitext
from collections import Counter


KB = 1024
MB = 1024 * 1024
GB = 1024 * 1024 * 1024


def show_unit(size):
    if size > GB:
        return "{:.2f}GB".format(float(size)/GB)
    if size > MB:
        return "{:.2f}MB".format(float(size)/MB)
    if size > KB:
        return "{:.2f}KB".format(float(size)/KB)

    return "{}B".format(size)

def cmp_less():
    pass

def cmp_more():
    pass

def walk(path):
    ext_sizes = Counter()

    # TODO: filte some directories
    for root, dirs, files in os.walk(path):
        for fname in files:
            name, ext = splitext(fname)
            if not ext:
                ext = name
            ext_sizes[ext] += getsize(join(root, fname))

    sorted_ext_sizes = sorted(ext_sizes.items(), lambda x, y: cmp(y[1], x[1]))

    total_size = sum(ext_sizes.values())

    print "[SUM]{:>31}{:>12}".format(total_size, show_unit(total_size))

    for ext, size in sorted_ext_sizes:
        print "{:<24}{:>12}{:>12}{:>8.2%}".format(ext, size, show_unit(size), float(size)/total_size)



if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Usage: {} path".format(sys.argv[0])
        sys.exit()

    walk(sys.argv[1])
